package com.wsx.java.boddy.agent.okhttp;

import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import okhttp3.Headers;
import okhttp3.Request;
import okhttp3.Response;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.concurrent.Callable;

/**
 * @author wangshuaixin
 * @Title: com.wsx.java.boddy.agent.okhttp.OkHttpInteceptor
 * @Description: TODO
 * @date 2019/02/19
 */
public class OkHttpInteceptor {

    @RuntimeType
    public static Response intercept(@Origin Method method,
                                     @SuperCall Callable<Response> callable,
                                     @AllArguments Object[] args) throws Exception {
        long start = System.currentTimeMillis();
        try {
            Request request = (Request) args[0];
            Field headersField = Request.class.getDeclaredField("headers");
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(headersField, headersField.getModifiers() & ~Modifier.FINAL);

            headersField.setAccessible(true);
            Headers.Builder headerBuilder = request.headers().newBuilder();
            headerBuilder.add("service_name", "");

            headersField.set(request, headerBuilder.build());
            return callable.call();
        } finally {
            System.out.println(method +" took times is " + (System.currentTimeMillis() - start));
        }
    }
}
